package com.gpay.erp.web.control;

import com.gpay.erp.core.dao.page.PageHelper;
import com.gpay.erp.core.dao.page.PagerModel;
import com.gpay.erp.core.system.bean.SysUser;
import com.gpay.erp.services.common.GlobalStatus;
import com.gpay.erp.services.common.impl.SystemConstant;
import com.gpay.erp.services.purchase.ContractService;
import com.gpay.erp.services.purchase.ContractSubService;
import com.gpay.erp.services.purchase.bean.Contract;
import com.gpay.erp.services.purchase.bean.ContractSub;
import com.gpay.erp.web.util.WebUtil;
import com.gpay.erp.web.vo.ChangeStatus;
import com.gpay.erp.web.vo.ContractDelete;
import com.gpay.erp.web.vo.ContractMode;
import com.gpay.erp.web.vo.ResponseInfo;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.support.RequestContext;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;

/**
 * Created by COMROSE on 2015/8/25 0025. 采购合同模块
 */
@Controller
@RequestMapping("/purchase/")
public class ContractController extends BaseController {
    private Log log = LogFactory.getLog(ContractController.class);
    @Autowired
    private ContractService contractService;
    @Autowired
    private ContractSubService contractSubService;
    @Autowired
    private GlobalStatus globalStatus;

    // 页面跳转 合同管理
    @RequestMapping("contractList")
    public String contractList() {
        return "purchase/contractList";
    }

    // 页面跳转 采购申请列表
    @RequestMapping("checkList")
    public String checkList() {
        return "purchase/applicationApprove";
    }

    // 页面跳转 采购新增
    @RequestMapping("contractAdd")
    public String orderAdd() {
        return "purchase/contractAdd";
    }

    // 页面跳转 供应商查询
    @RequestMapping("supplisersSelect")
    public String supplisersSelect() {
        return "system/suppliers/supSelect";
    }

    // 页面跳转 采购合同明细页面
    @RequestMapping("contractUpdate")
    public String contractUpdate(String id, ModelMap modelMap) {
        modelMap.addAttribute("contractId", id);
        return "purchase/contractAdd";
    }

    /**
     * 采购入库查询 返回单表list
     * @param contractSub
     * @param pageHelper
     * @param request
     * @param response
     * @throws IOException
     */
    @RequestMapping("selectPageContractSubList")
    public void selectPageContractSubList(ContractSub contractSub, PageHelper pageHelper,
                                       HttpServletRequest request, HttpServletResponse response)
            throws IOException {
        log.info("selectPageContractSubList start");
        RequestContext requestContext = new RequestContext(request);
        ResponseInfo responseInfo = new ResponseInfo();
        String result ="";
        String message = "";
        if(pageHelper.getOrder()==""||null == pageHelper.getOrder())
        {
            pageHelper.setOrder("id");
            pageHelper.setSort("desc");
        }
        contractSub.setFromRow((pageHelper.getPage() - 1) * pageHelper.getRows());
        contractSub.setToRow(pageHelper.getPage() * pageHelper.getRows());
//        contract.setFromRow(0);
//        contract.setToRow(9);
        if ("".equals(contractSub.getStatusSub())||null == contractSub.getStatusSub()){
            contractSub.setStatusSub("1");
        }
        contractSub.setSort(pageHelper.getSort());
        contractSub.setOrder(pageHelper.getOrder());
        PagerModel pagerModel = contractSubService.selectPageList(contractSub);
        if (pagerModel != null) {
            result = "00010";
            message = requestContext.getMessage("select.success");
            responseInfo.setObject(pagerModel);
        } else {
            result = "11111";
            message = requestContext.getMessage("no.data");
            responseInfo.setObject(pagerModel);
        }
        responseInfo.setResult(result);
        responseInfo.setMessage(message);
        log.info("selectPageContractSubList end");
        WebUtil.responseToJson(response, responseInfo);
    }
    /**
     * 采购合同查询 返回单表list
     * @param contract
     * @param pageHelper
     * @param request
     * @param response
     * @throws IOException
     */
    @RequestMapping("selectPageContractList")
    public void selectPageContractList(Contract contract, PageHelper pageHelper,
                                       HttpServletRequest request, HttpServletResponse response)
            throws IOException {
        log.info("selectPageContractList start");
        RequestContext requestContext = new RequestContext(request);
        ResponseInfo responseInfo = new ResponseInfo();
        if(pageHelper.getOrder()==""||null == pageHelper.getOrder())
        {
            pageHelper.setOrder("id");
            pageHelper.setSort("desc");
        }
        contract.setFromRow((pageHelper.getPage() - 1) * pageHelper.getRows());
        contract.setToRow(pageHelper.getPage() * pageHelper.getRows());
//        contract.setFromRow(0);
//        contract.setToRow(9);
        contract.setSort(pageHelper.getSort());
        contract.setOrder(pageHelper.getOrder());
        PagerModel pagerModel = contractService.selectPageList(contract);
        if (pagerModel != null) {
            for (Object hashMap1 : pagerModel.getRows()) {
                Contract hashMap = (Contract) hashMap1;
				String statusCode = globalStatus.getContractStatus(Integer.parseInt(hashMap.getContractStatus()));
				hashMap.setContractStatus(statusCode);
            }
            responseInfo.setResult("00010");
            responseInfo
                    .setMessage(requestContext.getMessage("select.success"));
            responseInfo.setObject(pagerModel);
        } else {
            responseInfo.setResult("11111");
            responseInfo.setMessage(requestContext.getMessage("no.data"));
            responseInfo.setObject(pagerModel);
        }
        log.info("selectPageContractList end");
        WebUtil.responseToJson(response, responseInfo);
    }
    /**
     * 添加合同子项 点击子项保存按钮
     * @param request
     * @param response
     * @throws IOException
     */
    @RequestMapping("saveContractSub")
    public void saveContractSub(@RequestBody ContractMode contractMode,
                                   HttpServletRequest request, HttpServletResponse response) {
        log.info("saveContractSub start");
        RequestContext requestContext = new RequestContext(request);
        ResponseInfo responseInfo = new ResponseInfo();
        HttpSession session = request.getSession();
        SysUser sysUser = (SysUser) session.getAttribute("loginUser");
        int insertId =1;
        if (contractMode != null) {
            //组织合同数据
            Contract contract = contractMode.getContract();
            String contractCode =contractService.getContractCode();
            contract.setContractCode(contractCode); //生成合同号
            contract.setContractStatus(SystemConstant.CONTRACTSTATUSEXEU); //合同执行状态
            contract.setAccountName(sysUser.getAccountName());
            contract.setF_account(sysUser.getF_account());
            contract.setAmountPaid(0.0);
            contract.setAmountApplication(0.0);
            //组织合同子项数据
               List<ContractSub> contractSubList = contractMode.getContractSubList(); //生成合同子项号码
                for(ContractSub contractSub:contractSubList)
                {
                    contractSub.setStatusSub("1");
                    contractSub.setAccountName(sysUser.getAccountName());
                    contractSub.setF_account(sysUser.getF_account());
                    contractSub.setProviderName(contract.getProviderName());
                    contractSub.setUserName(contract.getUserName());
                    contractSub.setSignDept(contract.getSignDept());
                    contractSub.setOrderDate(contract.getContractDate());

                }
            insertId = contractService.saveContractSubList(contract,contractSubList); //数据库保存
            }
        if (insertId != 1) {
                selectContractSub(String.valueOf(insertId), request, response);
        } else {
            responseInfo.setResult("00041");
            responseInfo.setMessage(requestContext.getMessage("add.fail"));
            responseInfo.setObject(insertId);
            WebUtil.responseToJson(response, responseInfo);
        }
        log.info("saveContractSub end");
    }

    /**
     * 点击采购合同子项详细查询
     * @param id 采购申请id
     * @param request
     * @param response
     * @throws IOException
     */
    @RequestMapping("selectContractSub")
    public void selectContractSub(String id,
                                  HttpServletRequest request, HttpServletResponse response)
            {
        log.info("selectContractSub start");
        RequestContext requestContext = new RequestContext(request);
        ResponseInfo responseInfo = new ResponseInfo();
        if (id == null) {
            id = "1";
        }
        Contract contract = contractService.selectById(id);
		String statusCode = globalStatus.getContractStatus(Integer.parseInt(contract.getContractStatus()));
		contract.setContractStatus(statusCode);
		List<ContractSub> listA = contractSubService.selectListByfid(id);
		for(ContractSub contractSub:listA)
		{
            contractSub.setStatusSub(globalStatus.getContractStatus(Integer.parseInt(contractSub.getStatusSub())));//状态转换
		}
        ContractMode contractMode = new ContractMode();
        contractMode.setContract(contract);
        contractMode.setContractSubList(listA);
		if (contractMode != null) {
			responseInfo.setResult("00010");
			responseInfo
					.setMessage(requestContext.getMessage("select.success"));
			responseInfo.setObject(contractMode);
		} else {
			responseInfo.setResult("11111");
			responseInfo.setMessage(requestContext.getMessage("no.data"));
			responseInfo.setObject(contractMode);
		}
        log.info("selectContractSub end");
        WebUtil.responseToJson(response, responseInfo);
    }

    /**
     * 合同明细点击保存按钮
     * @param request
     * @param response
     * @throws IOException
     */
    @RequestMapping("saveUpdateContractSub")
    public void saveUpdateContractSub(@RequestBody ContractMode contractMode,
                                HttpServletRequest request, HttpServletResponse response) {
        log.info("saveUpdateContractSub start");
        RequestContext requestContext = new RequestContext(request);
        ResponseInfo responseInfo = new ResponseInfo();
        HttpSession session = request.getSession();
        SysUser sysUser = (SysUser) session.getAttribute("loginUser");
        int updateId =1;
        if (contractMode != null) {
            //组织合同数据
            Contract contract1 = contractService.selectById(contractMode.getContract().getId());
            if ("1".equals(contract1.getContractStatus())) {
                Contract contract = contractMode.getContract();
//            String contractCode =contractService.getContractCode();
//            contract.setContractCode(contractCode); //生成合同号
                contract.setContractStatus(SystemConstant.CONTRACTSTATUSEXEU); //合同执行状态
                contract.setAmountPaid(contract1.getAmountPaid());
                contract.setAmountApplication(contract1.getAmountApplication());
                contract.setAccountName(sysUser.getAccountName());
                contract.setF_account(sysUser.getF_account());
                //组织合同子项数据
                List<ContractSub> contractSubList = contractMode.getContractSubList();
                for (ContractSub contractSub : contractSubList) {
                    contractSub.setContractNumber(contract.getContractCode());
                    contractSub.setAccountName(sysUser.getAccountName());
                    contractSub.setF_account(sysUser.getF_account());
                    contractSub.setUserName(contract.getUserName());
                    contractSub.setSignDept(contract.getSignDept());
                    contractSub.setOrderDate(contract.getContractDate());
                    contractSub.setProviderName(contract.getProviderName());
                    contractSub.setProviderCode(contract.getProviderCode());
                }
                updateId = contractService.saveUpdateContractSub(contract, contractSubList); //数据库保存
                selectContractSub(String.valueOf(updateId), request, response);
            } else {
                responseInfo.setResult("00041");
                responseInfo.setMessage(requestContext.getMessage("application.service.fail"));
                responseInfo.setObject(updateId);
                WebUtil.responseToJson(response, responseInfo);
            }
        }
        log.info("saveUpdateContractSub end");
    }
    /**
     * 采购申请详细子页面 点击删除一行记录
     */
    @RequestMapping("deleteOneContractSub")
    public void deleteOneContractSub(@RequestBody ContractDelete contractDelete,
                                        HttpServletRequest request, HttpServletResponse response) {
        log.info("deleteOneContractSub start");
        RequestContext requestContext = new RequestContext(request);
        ResponseInfo responseInfo = new ResponseInfo();
        int updateId = 1;
        if (contractDelete != null) {
            updateId = contractService.deleteOneContractSub(contractDelete.getContractId(),contractDelete.getContractSubIds());
            if (updateId !=1)
            {
                selectContractSub(contractDelete.getContractId(), request, response);

            }
        } else {
            responseInfo.setResult("00041");
            responseInfo.setMessage(requestContext.getMessage("add.fail"));
            responseInfo.setObject(updateId);
            WebUtil.responseToJson(response, responseInfo);
        }
        log.info("deleteOneContractSub end");
    }

    /**
     * 点击页面收货完成 收货完成撤销 结算完成 结算完成撤销 调用统一接口
     * 目前这个功能还没有完成。后续开发
     */
    @RequestMapping("updateChangeStatus")
    public void updateChangeStatus(ChangeStatus changeStatus,
                                     HttpServletRequest request, HttpServletResponse response) {
        log.info("updateChangeStatus start");
        //TODO
        RequestContext requestContext = new RequestContext(request);
        ResponseInfo responseInfo = new ResponseInfo();
        int updateId = 1;
        responseInfo.setResult("00041");
        responseInfo.setMessage(requestContext.getMessage("module.add"));
        responseInfo.setObject(updateId);
        log.info("updateChangeStatus end");
        WebUtil.responseToJson(response, responseInfo);
    }
}
